/**
 * ==================================
 * 行政区域排行
 * ==================================
 */
import {
  forwardRef,
  useEffect,
  useImperativeHandle,
  useRef,
  useState
} from 'react'

import districRankNodataPng from '@/assets/icons/safeCoGovernance/districRankNodata.png'
import { uuid } from '@/utils/YunMaiUtils'

// import { clearInterval } from "timers"
import type {
  AssociationData,
  SwitchAndIntervalRef
} from '../../../BigScreenBase/interface'
import DisplayCard from '../../Components/DisplayCard'
import type { IDistrictRankItem } from '../../data'
import { getDistrictRank } from '../../data'
import RankBannerItem from '../Compoents/RankBannerItem'

import './index.less'

export type AdministrativeAreaRankingProps = {
  selectedAssociationItem: AssociationData
}

export interface IDistrictRankItemRender extends IDistrictRankItem {
  prevAverage: number
  prevMaxVverage: number
  rankDataIndex: number
}

const DEFAULTRANKITEM: IDistrictRankItemRender = {
  regionCode: '',
  regionName: '',
  average: 0,
  prevAverage: 0,
  prevMaxVverage: 0,
  rankDataIndex: 0
}

const AdministrativeAreaRanking = forwardRef<
  SwitchAndIntervalRef,
  AdministrativeAreaRankingProps
>((props, ref) => {
  const {
    selectedAssociationItem: { key }
  } = props
  const [rankMaxAverage, setRankMaxAverage] = useState<number>(0)
  const [rankDataList, setRankDataList] = useState<IDistrictRankItemRender[]>(
    []
  ) //排行数据一维数组
  const [rankGroupList, setRankGroupList] = useState<
    IDistrictRankItemRender[][]
  >([]) //排行数据7个为一组的二维数组
  const [rankDataHasLoaded, setRankDataHasLoaded] = useState<boolean>(false)

  const autoplayIntervalIdRef = useRef<any>() //自动轮播interval
  const loopPlayDelayTimeoutRef = useRef<any>() //轮播一轮结束后，重新请求接口，延迟2s后重新开始轮播
  const noBannerIntervalIdRef = useRef<any>() //没有轮播时，5分钟请求一次接口

  const activeIndexRef = useRef<number>(0)
  const [activeIndex, setActiveIndex] = useState<number>(0)

  function _clearIntervalAndTimeout() {
    if (autoplayIntervalIdRef.current) {
      clearInterval(autoplayIntervalIdRef.current)
    }
    if (loopPlayDelayTimeoutRef.current) {
      clearTimeout(loopPlayDelayTimeoutRef.current)
    }
    if (noBannerIntervalIdRef.current) {
      clearInterval(noBannerIntervalIdRef.current)
    }
  }

  //行政区域排行接口
  function _getDistrictRankFn(entIdParam: string) {
    setRankDataHasLoaded(false)
    _clearIntervalAndTimeout()
    setActiveIndex(0)
    activeIndexRef.current = 0
    getDistrictRank({ entId: entIdParam })
      .then((res) => {
        const { data } = res
        // console.log("--data--:", data)
        if (!data || !data.length) {
          setRankDataList([])
          setRankGroupList([])
          return
        }

        const prevMaxVverage = rankMaxAverage
        setRankMaxAverage(data[0].average ?? 0)
        const tempRankDataList = data.map((dataItem, dataIndex) => {
          const { regionCode } = dataItem
          const prevRankDetail = rankDataList.find(
            (prevDataItem) => prevDataItem.regionCode === regionCode
          )
          const tempPrevAverage = prevRankDetail ? prevRankDetail.average : 0
          return {
            ...dataItem,
            rankDataIndex: dataIndex,
            prevAverage: tempPrevAverage,
            prevMaxVverage
          }
        })
        setRankDataList(tempRankDataList)

        //分组
        const tempRankGroupList = tempRankDataList.reduce(
          (
            prev: IDistrictRankItemRender[][],
            curr: IDistrictRankItemRender,
            index: number,
            array: IDistrictRankItemRender[]
          ) => {
            const groupIndex = Math.floor(index / 14)
            if (!prev[groupIndex]) {
              prev[groupIndex] = []
            }
            prev[groupIndex].push(curr)
            return prev
          },
          []
        )

        //groupItem 不足14项，补全
        const tempRankDataListLength = tempRankDataList.length
        const lastGroupItemLength =
          tempRankGroupList[tempRankGroupList.length - 1].length
        const needAddCount = 14 - lastGroupItemLength
        if (needAddCount) {
          for (let i = 0; i < needAddCount; i++) {
            tempRankGroupList[tempRankGroupList.length - 1].push({
              ...DEFAULTRANKITEM,
              regionCode: uuid(),
              rankDataIndex: tempRankDataListLength + i
            })
          }
        }
        // console.log("---tempRankGroupList--:", tempRankGroupList)
        setRankGroupList(tempRankGroupList)
        if (tempRankGroupList.length > 1) {
          //轮播
          loopPlayDelayTimeoutRef.current = setTimeout(() => {
            //轮播一轮结束后，重新请求接口，延迟3s后重新开始轮播
            autoplayIntervalIdRef.current = setInterval(() => {
              if (activeIndexRef.current >= tempRankGroupList.length - 1) {
                if (autoplayIntervalIdRef.current) {
                  clearInterval(autoplayIntervalIdRef.current)
                  _getDistrictRankFn(entIdParam)
                }
                activeIndexRef.current = 0
              } else {
                activeIndexRef.current += 1
              }
              setActiveIndex(activeIndexRef.current) //activeIndex === 0,_processIndex(1) 、1,_processIndex(2) 、2,_processIndex(3) 先累加再执行_processIndex
            }, 30000)
          }, 3000)
        } else {
          noBannerIntervalIdRef.current = setInterval(() => {
            //没有banner5分钟请求一次
            _getDistrictRankFn(entIdParam)
          }, 300000)
        }
      })
      .catch((err) => {
        console.error(
          '--AdministrativeAreaRanking--getDistrictRank--err--:',
          err
        )
        setRankMaxAverage(0)
        setRankDataList([])
        setRankGroupList([])
      })
      .finally(() => {
        setRankDataHasLoaded(true)
      })
  }

  //点击测试
  // const handleRunBanner = () => {
  //   if (activeIndexRef.current >= rankGroupList.length - 1) {
  //     activeIndexRef.current = 0
  //   } else {
  //     activeIndexRef.current += 1
  //   }
  //   setActiveIndex(activeIndexRef.current)
  // }

  useEffect(() => {
    _getDistrictRankFn(key)
    return () => {
      _clearIntervalAndTimeout()
    }
  }, [])

  useImperativeHandle(ref, () => ({
    switchAssociation: (newAssociationKey) => {
      _getDistrictRankFn(newAssociationKey)
    },
    intervalRefresh: () => {}
  }))

  //鼠标移入停止
  const handleBannerMouseEnter = (event: React.MouseEvent) => {
    if (autoplayIntervalIdRef.current) {
      clearInterval(autoplayIntervalIdRef.current)
    }
  }

  //移除轮播
  const handleBannerMouseLeave = (event: React.MouseEvent) => {
    autoplayIntervalIdRef.current = setInterval(() => {
      if (activeIndexRef.current >= rankGroupList.length - 1) {
        activeIndexRef.current = 0
      } else {
        activeIndexRef.current += 1
      }
      setActiveIndex(activeIndexRef.current)
    }, 30000)
  }

  return (
    <DisplayCard
      title="行政区域排行"
      height={431}
      bodyStyle={{
        width: '100%',
        height: '389px',
        boxSizing: 'border-box',
        padding: '24px'
      }}
    >
      <div
        className="center-distric-rank-group"
        // onClick={handleRunBanner}
        onMouseEnter={(event) => {
          handleBannerMouseEnter?.(event)
        }}
        onMouseLeave={(event) => {
          handleBannerMouseLeave?.(event)
        }}
      >
        {!rankGroupList.length && rankDataHasLoaded ? (
          <div className="center-distric-rank-nodata">
            <img src={districRankNodataPng} alt="暂无数据" />
            <p>暂无行政区域排行</p>
          </div>
        ) : (
          rankGroupList.map((groupItem, groupIndex) => (
            <RankBannerItem
              groupItem={groupItem}
              key={groupIndex}
              groupIndex={groupIndex}
              rankMaxAverage={rankMaxAverage}
              activeIndex={activeIndex}
              groupLength={rankGroupList.length}
            />
          ))
        )}
      </div>
    </DisplayCard>
  )
})

export default AdministrativeAreaRanking
